<?php
declare (strict_types = 1);

namespace app\middleware;

use app\common\exception\LogicException;

/**
 * 检查用户是否已经登录
 */
class CheckAdminLogin
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //判断是否传token
        $token = $request->header('token');
        if (!$token) {
            throw new LogicException('登录已过期，请重新登录');
        }

        //判断token是否过期
        $tokenData = Cache()->get($token);
        if (!$tokenData) {
            throw new LogicException('登录已过期，请重新登录');
        }

        //更新token过期时间
        Cache()->set($token, $tokenData, 86400);

        $tokenData = json_decode($tokenData, true);
        $request->admin_info = $tokenData['admin_info'];
        
        return $next($request);
    }
}
